<template>
  <div class="tree_container">
    <el-tree
      ref="tree"
      :data="data"
      v-loading="loading"
      node-key="id"
      :props="props"
      show-checkbox
      :check-strictly="checkStrictly"
      @check-change="handleCheckChange"
      :default-expanded-keys="defaultCheckedKeys"
    >
    </el-tree>
  </div>
</template>

<script>

import menuApi from '@/api/auth/menuApi'

export default {
  name: "menuSelector",
  model: {
    prop: 'defaultCheckedKeys',
    event: 'change'
  },
  props: {
    defaultCheckedKeys: {
      type: Array,
    }
  },
  watch: {
    defaultCheckedKeys: {
      handler(value) {
        if (Array.isArray(value)) {
          this.$nextTick(_=>{
            this.$refs.tree.setCheckedKeys(value, true)
            console.error('watcher!',value)
          })
        }else{
          this.$nextTick(_=> {
            console.error('watcher!!!!', value)
          })
          // this.$refs.tree.setCheckedKeys([])
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      data: [],
      loading: false,
      props: {
        label: 'name',
        children: 'children',
        currentIds: [],
      },
      count: 0
    }
  },
  methods: {
    getData() {
      this.loading = true
      // 获取菜单树
      menuApi.getTree().then(res => {
        this.data = res.data
      }).finally(_ => {
        this.loading = false
      })
    },
    handleCheckChange() {
      this.$emit('change', this.$refs.tree.getCheckedKeys(false).concat(this.$refs.tree.getHalfCheckedKeys()))
    },
    // 组件重置
    reset(){
      this.count = 0
      // 所有节点收起
      Object.values(this.$refs.tree.store.nodesMap).forEach(node => {
        node.expanded = false
      })
      // 其他暂未想到...
    }
  },
  created() {
    this.getData()
  }

}
</script>

<style scoped>
.tree_container {
  border: 1px solid #C0C4CC;
  max-height: 400px;
  overflow: auto;
  /* 这里是因为element中的el-form-item__content 设置的line-height为40,与el-tree的高度26px不一致,导致出现滚动条的问题(行内块元素的height与line-height应该一致) */
  line-height: 26px;
  border-radius: 4px;
}
</style>
